<template>
  <el-dialog
    :title="view === 'create'? '新增': '编辑'"
    :visible="true"
    custom-class="dialogWrapper"
    :before-close="closeDialog"
    >
    <el-form :model="formData" label-width="80px" ref="ruleForm" :rules="rules">
     <el-form-item label="角色名称" prop="roleName" required>
        <el-input v-model="formData.roleName" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="角色类型" prop="roleType" required v-if=" view === 'create'">
        <el-select v-model="formData.roleType">
          <el-option v-for="(item, index) in ['管理员', '操作员']" :value="String(index)" :label="item" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户描述" prop="roleDesc" required>
        <el-input
          v-model="formData.roleDesc"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
         auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="设置权限" prop="checkPass">
        <el-tree
          ref="tree"
          :data="menus"
          show-checkbox
          node-key="menuId"
          :default-checked-keys="list"
          :props="{label: 'menuName', children: 'sysOperation'}"
        ></el-tree>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { create, edit } from "@/services/roles";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
// import {login} from '@/services/login'
// import menuModules from '@/router/modules.json'
export default {
  name: "edit-role",
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    }
    return {
      menus: [],
      list: [],
      formData: {
        roleName: "",
        roleType: "",
        roleDesc: ""
      },
      menuInfo: [],
      dialogFormVisible: false,
      rules: {
        roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
        roleType: [{ required: true, message: "请输入角色类型", trigger: "blur" }],
        roleDesc: [{ required: true, message: "请输入角色描述", trigger: "blur" }],
        checkPass: [
            { validator: validatePass2, trigger: 'blur' }]
      }
    }
  },
  // data: () => ({
  //   menus: [],
  //   list: [],
  //   formData: {
  //     roleName: "",
  //     roleType: "",
  //     roleDesc: ""
  //   },
  //   menuInfo: [],
  //   dialogFormVisible: false,
  //   rules: {
  //     roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  //     roleType: [{ required: true, message: "请输入角色类型", trigger: "blur" }],
  //     roleDesc: [{ required: true, message: "请输入角色描述", trigger: "blur" }]
  //   }
  // }
  // ),
  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    closeDialog() {
      this.$emit("close");
    },
    menuList(arr) {
      arr.forEach(val => {
        if (val.isChoose === "0") {
          this.list.push(val.menuId);
          if (val.sysOperation) {
            this.menuList(val.sysOperation);
          }
        } else {
          if (val.sysOperation) {
            this.menuList(val.sysOperation);
          }
        }
      });
    },
    getMenuInfo(menus, roleMenu) {
      roleMenu.push(27);
      if (menus instanceof Array && menus.length > 0) {
        menus.filter(items => {
          if (roleMenu.includes(items.menuId) && items.menuName) {
            let userInfo = {
              menuNo: items.menuNo,
              menuNameCh: items.menuName,
              parentId: items.parentId,
              reorder: items.reorder
            };
            this.menuInfo.push(userInfo);
            this.getMenuInfo(items.sysOperation, roleMenu);
          }
        });
      }
    },
    submit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            let roleMenu = this.$refs.tree.getCheckedKeys();
            let rms = { menuId: roleMenu };
            if (this.view === "create") {
              await create({
                roleName: this.formData.roleName,
                roleType: this.formData.roleType,
                roleDesc: this.formData.roleDesc,
                roleMenu: rms
              });
            } else {
              let roleMenu = this.$refs.tree.getCheckedKeys();
              let rms = { menuId: roleMenu };
              await edit({
                id: this.formData.id,
                roleName: this.formData.roleName,
                roleType: this.formData.roleType,
                roleMenu: rms,
                roleDesc: this.formData.roleDesc
              });
              this.getMenuInfo(this.menus, roleMenu);
              this.setUserInfo({ menuList: this.menuInfo });
            }
            this.dialogFormVisible = false;
            this.$emit("close", true);
            this.$message({
              showClose: true,
              message: "提交成功",
              type: "success"
            });
          } catch (e) {
            // this.$alert(e.message, "提示", {
            //   type: "error",
            //   confirmButtonText: "确定"
            // });
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    }
  },
  mounted() {}
};
</script>
<style>
.dialogWrapper {
  width: 540px;
}
.el-select {
  width: 100%;
}
</style>
